using Microsoft.AspNetCore.SignalR;
using System.Collections.Concurrent;

namespace OrderingSystem.API.Hubs
{
    public class NotificationHub : Hub
    {
        private static readonly ConcurrentDictionary<string, string> _userConnections = new();
        private static readonly ConcurrentDictionary<string, HashSet<string>> _roleConnections = new();

        public override async Task OnConnectedAsync()
        {
            var userId = Context.User?.FindFirst("sub")?.Value;
            if (!string.IsNullOrEmpty(userId))
            {
                _userConnections.TryAdd(userId, Context.ConnectionId);
            }

            var roles = Context.User?.FindAll("role").Select(c => c.Value);
            if (roles != null)
            {
                foreach (var role in roles)
                {
                    _roleConnections.AddOrUpdate(
                        role,
                        new HashSet<string> { Context.ConnectionId },
                        (_, connections) =>
                        {
                            connections.Add(Context.ConnectionId);
                            return connections;
                        });
                }
            }

            await base.OnConnectedAsync();
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            var userId = Context.User?.FindFirst("sub")?.Value;
            if (!string.IsNullOrEmpty(userId))
            {
                _userConnections.TryRemove(userId, out _);
            }

            var roles = Context.User?.FindAll("role").Select(c => c.Value);
            if (roles != null)
            {
                foreach (var role in roles)
                {
                    _roleConnections.AddOrUpdate(
                        role,
                        new HashSet<string>(),
                        (_, connections) =>
                        {
                            connections.Remove(Context.ConnectionId);
                            return connections;
                        });
                }
            }

            await base.OnDisconnectedAsync(exception);
        }

        public static string GetUserConnectionId(string userId)
        {
            _userConnections.TryGetValue(userId, out var connectionId);
            return connectionId;
        }

        public static IEnumerable<string> GetRoleConnectionIds(string role)
        {
            if (_roleConnections.TryGetValue(role, out var connections))
            {
                return connections;
            }
            return Enumerable.Empty<string>();
        }
    }
} 